package com.graph;

import java.util.LinkedList;

public class Solution1926 {
    public int nearestExit(char[][] maze, int[] entrance) {
        int[] dx = new int[]{-1, 1, 0, 0};
        int[] dy = new int[]{0, 0, -1, 1};
        LinkedList<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[maze.length][maze[0].length];
        visited[entrance[0]][entrance[1]] = true;
        queue.add(entrance);
        int res = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            res++;
            for (int i = 0; i < size; i++) {
                int[] cur = queue.removeFirst();
                for (int j = 0; j < 4; j++) {
                    int x = cur[0] + dx[j];
                    int y = cur[1] + dy[j];
                    if (x < 0 || x >= maze.length || y < 0 || y >= maze[0].length) continue;
                    if (visited[x][y] || maze[x][y] != '.') continue;
                    if (x == 0 || x == maze.length - 1 || y == 0 || y == maze[0].length - 1) return res;
                    queue.add(new int[]{x, y});
                    visited[x][y] = true;
                }
            }
        }
        return -1;
    }
}
